package example.neon;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class JPanelCollapse extends JPanel {
    JPanelCollapseHead collapseHead;
    JPanel collapseContent;
    public boolean isActive;

    public JPanelCollapse(String title, JPanel collapseContent, boolean isActive) {
        this.isActive = isActive;
        collapseHead = new JPanelCollapseHead(title);
        collapseHead.addMouseListener(createHeadMouseListener());
        this.add(collapseHead);
        this.collapseContent = collapseContent;
        this.setBorder(BorderFactory.createEmptyBorder(0, 0, 10, 0));
        this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
        if (isActive) {
            this.add(collapseContent);
        } else {
            collapseHead.iconRotate(-90);
        }
    }

    public MouseAdapter createHeadMouseListener() {
        JPanelCollapse self = this;
        return new MouseAdapter() {
            @Override
            public void mouseEntered(MouseEvent e) {
                super.mouseEntered(e);
                self.collapseHead.setBackground(Color.BLACK);
            }

            @Override
            public void mouseExited(MouseEvent e) {
                super.mouseExited(e);
                collapseHead.setBackground(null);
            }

            @Override
            public void mouseClicked(MouseEvent e) {
                super.mouseClicked(e);
                // head图标旋转
                collapseHead.iconRotate(isActive ? -90 : 90);
                isActive = !isActive;
                collapseHead.repaint();
                // 抽屉内容展开或关闭
                if (isActive)
                    self.add(collapseContent);
                else
                    self.remove(collapseContent);
                self.revalidate();
            }
        };
    }
}
